package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lineng.dao.MettingMapper;
import com.lineng.pojo.Metting;
import com.lineng.service.MettingService;
import com.lineng.util.UrlUtil;
import com.lineng.util.VerificationUtil;

@Service
public class MettingServiceImpl implements MettingService {

	@Autowired
	MettingMapper mettingMapper;

	@Autowired
	private HttpServletRequest request;

	public List<Metting> getMetting() {

		List<Metting> meettings = mettingMapper.selectByExample(null);
		if (VerificationUtil.verification(request) == 0) {
			for (int i = 0; i < meettings.size(); i++) {
				if (meettings.get(i).getReader() != null && meettings.get(i).getReader() != 0) {
					int result = meettings.get(i).getReader() + 1;
					mettingMapper.updateMettingReader(result);
				} else {
					mettingMapper.updateMettingReader(1);
				}
			}
		}
		return meettings;
	}

	public int insertMetting(Metting metting, String username) {
		if (VerificationUtil.verification(request) == 1) {
			metting.setDate(new Date());
			metting.setPeople(username);
			if (metting.getUrl().startsWith("http")) {
				return mettingMapper.insertSelective(metting);
			} else {
				metting.setUrl(UrlUtil.url(metting.getUrl()));
				return mettingMapper.insertSelective(metting);
			}

		}
		return 0;

	}

	public int updateMetting(Metting metting, String username) {
		if (VerificationUtil.verification(request) == 1) {
			metting.setDate(new Date());
			metting.setPeople(username);
			if (metting.getUrl().startsWith("http")) {
				return mettingMapper.updateByPrimaryKeySelective(metting);
			} else {
				metting.setUrl(UrlUtil.url(metting.getUrl()));
				return mettingMapper.updateByPrimaryKeySelective(metting);
			}
		}
		return 0;

	}

	public int deleteMetting(Integer[] idList) {
		if (VerificationUtil.verification(request) == 1) {
			return mettingMapper.deleteById(idList);
		}
		return 0;

	}
}
